<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot-scope="{row}" slot="menu">
<!--        <el-button-->
<!--          icon="el-icon-info"-->
<!--          type="text"-->
<!--          size="small"-->
<!--          @click.stop="handleOpenLog(row)"-->
<!--        >物流记录-->
<!--        </el-button>-->
        <el-button
          icon="el-icon-info"
          type="text"
          size="small"
          v-if="row.status === 2 && row.cancelConfirmTime === ''"
          @click.stop="handleCancelConfirmItem(row)"
        >取消确认
        </el-button>
      </template>
      <template slot="menuLeft">
        <el-date-picker
          style="margin-right: 10px; width: 200px !important; height: 32px; line-height: 32px;"
          v-model="date"
          align="right"
          unlink-panels
          value-format="yyyy-MM-dd">
        </el-date-picker>
        <el-button type="primary"
                   size="small"
                   plain
                   @click="handleGeneral">生成配送信息
        </el-button>
<!--        <el-button type="primary"-->
<!--                   size="small"-->
<!--                   plain-->
<!--                   @click="handleOrder">顺丰下单-->
<!--        </el-button>-->
        <el-button type="success"
                   size="small"
                   plain
                   @click="handlePrintOpen">订单打印
        </el-button>
        <el-button type="success"
                   size="small"
                   plain
                   @click="handleExport">导出顺丰订单
        </el-button>
<!--        <el-button type="danger"-->
<!--                   size="small"-->
<!--                   icon="el-icon-delete"-->
<!--                   plain-->
<!--                   v-if="permission.delivery_delete"-->
<!--                   @click="handleDelete">删 除-->
<!--        </el-button>-->
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="small"
          plain
          @click.stop="handleCancelSF()"
        >取消确认订单
        </el-button>
        <el-select style="width: 200px !important; margin-right: 10px" v-model="hasSpec" placeholder="请选择是否有个性餐" clearable>
          <el-option :value="1" label="有个性餐">有个性餐</el-option>
          <el-option :value="2" label="无个性餐">无个性餐</el-option>
        </el-select>
        <el-select style="width: 200px !important; margin-right: 10px" v-model="printStatus" placeholder="请选择是否已打印" clearable>
          <el-option :value="1" label="已打印">已打印</el-option>
          <el-option :value="0" label="未打印">未打印</el-option>
        </el-select>
<!--        <el-select style="width: 200px !important; margin-right: 10px" v-model="deliveryStatus" placeholder="请选择物流状态" clearable>-->
<!--          <el-option :value="'待揽收'" label="待揽收">待揽收</el-option>-->
<!--          <el-option :value="'运输中'" label="运输中">运输中</el-option>-->
<!--          <el-option :value="'已签收'" label="已签收">已签收</el-option>-->
<!--        </el-select>-->
        <el-input placeholder="昵称、电话" style="width: 200px; margin-right: 10px" v-model="nicknameAndPhone" clearable></el-input>
        <el-input placeholder="备注、扩展字段" style="width: 200px; margin-right: 10px" v-model="remark" clearable></el-input>
        <el-select v-model="searchMerchantId"
                   placeholder="门店"
                   style="margin-right: 10px; width: 200px !important; height: 32px; line-height: 32px;"
                   clearable
        >
          <el-option
            v-for="item in merchantOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <el-date-picker
          style="margin-right: 10px; width: 450px !important; height: 32px; line-height: 32px;"
          v-model="dateRange"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions">
        </el-date-picker>
        <el-button type="primary"
                   size="small"
                   @click="onLoad(page)">搜索
        </el-button>
        <el-switch
          v-model="showCancel"
          active-text="显示取消订单"
          @change="showCancelChange"
          inactive-text="">
        </el-switch>
      </template>
      <template slot-scope="{row}" slot="printStatus">
        <el-tag v-if="row.printStatus === 0" type="info" @click="updatePrintStatusConfirm(row)">未打印</el-tag>
        <el-tag v-if="row.printStatus === 1" type="success">已打印</el-tag>
      </template>
      <template slot-scope="{row}" slot="distance">
        <el-tag v-if="row.distance === 0" type="info">{{ row.distance }} km</el-tag>
        <el-tag v-else type="primary">{{ row.distance }} km</el-tag>
      </template>
      <template slot-scope="{row}" slot="hasSpec">
        <el-tag v-if="row.hasSpec === 1" type="success">有个性餐</el-tag>
        <el-tag v-if="row.hasSpec === 2" type="info">无个性餐</el-tag>
      </template>
      <template slot-scope="{row}" slot="status">
        <el-tag v-if="row.status === 1" type="success">正常</el-tag>
        <el-tag v-if="row.status === 2 && row.cancelConfirmTime !== ''" type="danger">已取消</el-tag>
        <el-tag v-if="row.status === 2 && row.cancelConfirmTime === ''" type="warning">取消未确认</el-tag>
      </template>
      <template slot-scope="{row}" slot="deliveryStatus">
        <el-tag v-if="row.deliveryStatus === 0" type="primary">待配送</el-tag>
        <el-tag v-else-if="row.deliveryStatus === 1" type="warning">配送中</el-tag>
        <el-tag v-else-if="row.deliveryStatus === 99" type="success">配送完成</el-tag>
        <el-tag v-else type="danger">未知</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="timeRange">
        <el-tag v-if="row.timeRange && row.timeRange !== ''" type="primary">{{ row.timeRange.replace(',', ' ~ ') }}</el-tag>
        <el-tag v-else type="info">未配置</el-tag>
      </template>
    </avue-crud>
    <el-dialog title="打单"
               append-to-body
               :visible.sync="printVisible"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :show-close="false"
               width="30%">
      <el-form :model="printForm" ref="form" label-width="80px" class="food-select-form">
        <el-form-item label="打印机: ">
          <el-select v-model="printer" style="width: 70%" @change="handlePrintChange">
            <el-option :key="item.name" v-for="item in printers" :label="item.name" :value="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单: ">
          <div :key="item.id" v-for="item in selectionList" style="margin-bottom: 10px">
            <span>收件人：</span><el-tag type="primary">{{ item.receiverName }}</el-tag>&nbsp;&nbsp;&nbsp;
            <span>快递单号：</span><el-tag :type="item.originNo && item.originNo !== '' ? 'primary' : 'danger'">{{ item.originNo && item.originNo !== '' ? item.originNo : '无' }}</el-tag>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handlePrintClose">取 消</el-button>
        <el-button type="primary" @click="handlePrint">打 印</el-button>
      </span>
    </el-dialog>
    <el-dialog title="物流记录"
               append-to-body
               :visible.sync="logVisible"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :show-close="false"
               width="30%">
      <el-timeline :reverse="true" v-loading="logLoading">
        <el-timeline-item
          v-for="(log, index) in logs"
          :key="index"
          :timestamp="log.acceptTime">
          {{log.remark}}
        </el-timeline-item>
      </el-timeline>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseLog">取 消</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, general, sfOrder, sfToken, updatePrintStatus, cancelSF, routesSF, cancelConfirm} from "@/api/delivery/delivery";
  import {getSelect as getMerchantList} from "@/api/merchant/merchant";
  import {mapGetters} from "vuex";
  import {dateFormat} from "../../util/date";
  import {hiprint} from "_vue-plugin-hiprint@0.0.50@vue-plugin-hiprint";
  import {getToken} from "@/util/auth";

  const sdkParams = {
    env: "pro",
    partnerID: "JMQSAPATNAFU",
    callback: () => {},
    notips: false
  }
  const printSdk = new SCPPrint(sdkParams);
  const baseTop = 20
  export default {
    data() {
      return {
        logLoading: false,
        logVisible: false,
        logs: [],
        printer: '',
        printers: [],
        sfAccessToken: '',
        printVisible: false,
        date: '',
        hasSpec: '',
        printStatus: '',
        deliveryStatus: '',
        showCancel: false,
        remark: '',
        nicknameAndPhone: '',
        searchMeal: '',
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 100,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          column: [
            {
              label: "日期",
              prop: "date",
              width: 120,
            },
            {
              label: "编号",
              prop: "code",
              overHidden: true,
              width: 150,
              display: false
            },
            {
              label: "距离",
              prop: "distance",
              overHidden: true,
              slot: true,
              width: 150,
              display: false
            },
            {
              label: "门店",
              prop: "merchantId",
              type: "select",
              dicUrl: '/api/merchant/merchant/select',
              props: {
                label: "name",
                value: "id"
              },
            },
            {
              label: "打单状态",
              prop: "printStatus",
              slot: true,
              display: false
            },
            {
              label: "收件人",
              prop: "receiverName",
              rules: [{
                required: true,
                message: "请输入收件人",
                trigger: "blur"
              }]
            },
            {
              label: "收件人手机",
              prop: "receiverPhone",
              width: 150,
              rules: [{
                required: true,
                message: "请输入收件人手机",
                trigger: "blur"
              }]
            },
            {
              label: "收件人地址",
              prop: "receiverAddress",
              width: 150,
              rules: [{
                required: true,
                message: "请输入收件人地址",
                trigger: "blur"
              }]
            },
            {
              label: "门牌",
              prop: "receiverAddressDetail",
              width: 150,
              rules: [{
                required: true,
                message: "请输入收件人地址",
                trigger: "blur"
              }]
            },
            {
              label: "送达时间",
              prop: "timeRange",
              row: true,
              slot: true,
              span: 24,
            },
            {
              label: "有个性餐",
              prop: "hasSpec",
              width: 150,
              slot: true,
              display: false
            },
            {
              label: "状态",
              width: 150,
              prop: "status",
              slot: true,
              display: false
            },
            {
              label: "配送状态",
              prop: "deliveryStatus",
              slot: true,
            },
            {
              label: "托寄物",
              prop: "depositum",
              rules: [{
                required: true,
                message: "请输入托寄物",
                trigger: "blur"
              }]
            },
            {
              label: "订单备注",
              prop: "orderRemark",
              width: 200,
              overHidden: true,
              rules: [{
                required: true,
                message: "请输入订单备注",
                trigger: "blur"
              }]
            },
            {
              label: "扩展字段1",
              prop: "remark1",
              overHidden: true,
              rules: [{
                required: true,
                message: "请输入扩展字段1",
                trigger: "blur"
              }]
            },
            {
              label: "创建时间",
              prop: "createTime",
              overHidden: true,
              display: false,
            },
            {
              label: "最后更新时间",
              prop: "updateTime",
              overHidden: true,
              display: false,
            },
          ]
        },
        data: [],
        dateRange: '',
        searchMerchantId: '',
        merchantOptions: [],
        pickerOptions: {
          shortcuts: [
            {
              text: '今日',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '明日',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() + 3600 * 1000 * 24);
                end.setTime(end.getTime() + 3600 * 1000 * 24);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '昨日',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24);
                end.setTime(end.getTime() - 3600 * 1000 * 24);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '最近一周',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', [start, end]);
              }
            }, {
              text: '最近一个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit('pick', [start, end]);
              }
            }, {
              text: '最近三个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit('pick', [start, end]);
              }
            }]
        },
        hiprint: {},
        // printTemplate: {"panels":[{"index":0,"height":60,"width":80,"paperHeader":0,"paperFooter":170.07874015748033,"printElements":[{"options":{"left":4.5,"top":39,"height":9.75,"width":103.5,"title":"编号","field":"code","testData":"1-111","fontSize":13.5},"printElementType":{"type":"text"}},{"options":{"left":111,"top":15,"height":67.5,"width":111,"title":"订单信息","field":"info","testData":"食材","fontSize":13.5,"lineHeight":14.25},"printElementType":{"type":"longText"}},{"options":{"left":6,"top":63,"height":9.75,"width":102,"title":"姓名","field":"receiver","testData":"张三","fontSize":13.5},"printElementType":{"type":"text"}},{"options":{"left":7.5,"top":88.5,"height":16.5,"width":103.5,"title":"距离","field":"distance","testData":"2公里","fontSize":13.5},"printElementType":{"type":"text"}},{"options":{"left":6,"top":115.5,"height":43.5,"width":210,"title":"地址","field":"address","testData":"福建省厦门市","fontSize":13.5,"lineHeight":14.25},"printElementType":{"type":"longText"}},{"options":{"left":6,"top":13.5,"height":13.5,"width":40.5,"field":"page","testData":"1 / 3","fontSize":13.5},"printElementType":{"type":"text"}}],"paperNumberLeft":196,"paperNumberTop":148,"paperNumberDisabled":true,"orient":2}]},
        // printTemplate: {"panels":[{"index":0,"height":60,"width":80,"paperHeader":0,"paperFooter":170.07874015748033,"printElements":[{"options":{"left":4.5,"top":39,"height":9.75,"width":103.5,"title":"编号","field":"code","testData":"1-111","fontSize":13.5},"printElementType":{"type":"text"}},{"options":{"left":111,"top":15,"height":67.5,"width":111,"title":"订单信息","field":"info","testData":"食材","fontSize":13.5,"lineHeight":14.25},"printElementType":{"type":"longText"}},{"options":{"left":4.5,"top":60,"height":9.75,"width":102,"title":"姓名","field":"receiver","testData":"张三三的女朋友","fontSize":9.75},"printElementType":{"type":"text"}},{"options":{"left":6,"top":96,"height":16.5,"width":103.5,"title":"距离","field":"distance","testData":"2公里","fontSize":13.5},"printElementType":{"type":"text"}},{"options":{"left":6,"top":115.5,"height":43.5,"width":210,"title":"地址","field":"address","testData":"福建省厦门市","fontSize":13.5,"lineHeight":14.25},"printElementType":{"type":"longText"}},{"options":{"left":6,"top":13.5,"height":13.5,"width":100.5,"field":"page","testData":"1 / 3","fontSize":13.5},"printElementType":{"type":"text"}},{"options":{"left":6,"top":78,"height":9.75,"width":102,"title":"电话","field":"telephone","testData":"13333333333","fontSize":9.75},"printElementType":{"type":"text"}}],"paperNumberLeft":196,"paperNumberTop":148,"paperNumberDisabled":true,"orient":2}]},
        // printTemplate: {"panels":[{"index":0,"height":60,"width":80,"paperHeader":0,"paperFooter":170.07874015748033,"printElements":[{"options":{"left":6,"top":12,"height":9.75,"width":103.5,"title":"姓名","field":"receiver","testData":"张三三的女朋友","fontSize":9.75},"printElementType":{"type":"text"}},{"options":{"left":135,"top":12,"height":10.5,"width":85.5,"field":"page","testData":"1 / 3","title":"页码","fontSize":9.75},"printElementType":{"type":"text"}},{"options":{"left":135,"top":45,"height":12,"width":85.5,"title":"编号","field":"code","testData":"1-111","fontSize":9.75},"printElementType":{"type":"text"}},{"options":{"left":6,"top":28.5,"height":12,"width":103.5,"title":"电话","field":"telephone","testData":"13333333333","fontSize":9.75},"printElementType":{"type":"text"}},{"options":{"left":6,"top":45,"height":12,"width":103.5,"title":"距离","field":"distance","testData":"2公里","fontSize":9.75},"printElementType":{"type":"text"}},{"options":{"left":6,"top":61.5,"height":18,"width":211.5,"title":"订单信息","field":"info","testData":"中式A餐+西式B餐","fontSize":11.25,"lineHeight":14.25},"printElementType":{"type":"longText"}},{"options":{"left":6,"top":84,"height":34.5,"width":211.5,"title":"备注","field":"remark","testData":"加饭","fontSize":11.25,"lineHeight":14.25},"printElementType":{"type":"longText"}},{"options":{"left":6,"top":124.5,"height":36,"width":210,"title":"地址","field":"address","testData":"福建省厦门市","fontSize":11.25,"lineHeight":14.25},"printElementType":{"type":"longText"}}],"paperNumberLeft":196,"paperNumberTop":148,"paperNumberDisabled":true,"orient":2}]},
        printTemplate: {"panels":[{"index":0,"height":110,"width":130,"paperHeader":0,"paperFooter":311.8110236220473,"printElements":[{"options":{"left":9,"top":10.5,"height":24,"width":219,"title":"姓名","field":"receiver","testData":"张三三的女朋友","fontSize":19.5},"printElementType":{"type":"text"}},{"options":{"left":234,"top":12,"height":21,"width":120,"field":"page","testData":"1 / 3","title":"页码","fontSize":12},"printElementType":{"type":"text"}},{"options":{"left":9,"top":40.5,"height":24,"width":220.5,"title":"电话","field":"telephone","testData":"13333333333","fontSize":19.5},"printElementType":{"type":"text"}},{"options":{"left":234,"top":54,"height":22.5,"width":120,"title":"编号","field":"code","testData":"1-111","fontSize":21.75,"fontWeight":"bolder"},"printElementType":{"type":"text"}},{"options":{"left":9,"top":72,"height":24,"width":220.5,"title":"距离","field":"distance","testData":"2公里","fontSize":19.5},"printElementType":{"type":"text"}},{"options":{"left":9,"top":105,"height":60,"width":312,"title":"地址","field":"address","testData":"厦门市湖里区新景国际外滩厦门市新景国际外滩42号502","fontSize":19.5,"lineHeight":19.5},"printElementType":{"type":"longText"}},{"options":{"left":9,"top":175.5,"height":48,"width":312,"title":"订单信息","field":"info","testData":"中式A餐+西式B餐","fontSize":19.5,"lineHeight":19.5},"printElementType":{"type":"longText"}},{"options":{"left":10.5,"top":234,"height":60,"width":309,"title":"备注","field":"remark","testData":"加饭","fontSize":19.5,"lineHeight":19.5},"printElementType":{"type":"longText"}}],"paperNumberLeft":338,"paperNumberTop":289,"paperNumberDisabled":true,"orient":2}]},
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: false,
          viewBtn: false,
          delBtn: false,
          editBtn: this.vaildData(this.permission.delivery_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    created() {
      const now = new Date()
      now.setTime(now.getTime())
      this.date = dateFormat(now)
      this.getMerchantList()

      if (hiprint.hiwebSocket.opened) {
        console.log("websocket is opened")
      } else {
        hiprint.hiwebSocket.setHost("http://localhost:17521")
      }
    },
    methods: {
      getMerchantList() {
        getMerchantList().then(res => {
          this.merchantOptions = res.data.data;
        })
      },
      updatePrintStatusConfirm(row) {
        this.$confirm(`确定将订单 ${row.id} 的打印状态修改为已打印?`, {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            updatePrintStatus(row.id).then(() => {
              this.onLoad(this.page)
            })
          })
      },
      showCancelChange() {
        this.onLoad(this.page)
      },
      handleOpenLog(val) {
        this.logVisible = true
        this.logLoading = true
        routesSF(val.id).then(res => {
          this.logs = res.data.data
          this.logLoading = false
        })
      },
      handleCloseLog() {
        this.logVisible = false
        this.logs = false
      },
      handlePrintChange(val) {
        // printSdk.setPrinter(val)
      },
      handleExport() {
        let params = '';
        if (this.dateRange && this.dateRange !== '') {
          params += `&startDate=${this.dateRange[0]}&endDate=${this.dateRange[1]}`
        }
        if (this.date && this.date !== '') {
          params += `&date=${this.date}`
        }
        if (this.hasSpec && this.hasSpec !== '') {
          params += `&hasSpec=${this.hasSpec}`
        }
        if (this.printStatus !== undefined && this.printStatus !== '') {
          params += `&printStatus=${this.printStatus}`
        }
        if (this.deliveryStatus && this.deliveryStatus !== '') {
          params += `&deliveryStatus=${this.deliveryStatus}`
        }
        if (this.remark && this.remark !== '') {
          params += `&remark=${this.remark}`
        }
        if (this.nicknameAndPhone && this.nicknameAndPhone !== '') {
          params += `&nicknameAndPhone=${this.nicknameAndPhone}`
        }
        if (this.ids && this.ids !== '') {
          params += `&ids=${this.ids}`
        }
        this.$confirm("是否导出数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          window.open(`/api/celery-delivery/delivery/export-delivery-sf?blade-auth=${getToken()}${params}`);
        });
      },
      handlePrintOpen() {
        if (hiprint.hiwebSocket.opened) {
          this.printVisible = true
          this.printers = hiprint.hiwebSocket.getPrinterList()
          return;
        }

        this.handlePrint()
      },
      handlePrintClose() {
        this.printVisible = false
        this.printForm = {}
        this.printer = ''
        this.printers = []
      },
      handlePrint() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择需要打印的订单")
          return
        }
        const originNoList = this.selectionList.map(e => e.originNo)
        if (originNoList.includes(undefined) || originNoList.includes('') || originNoList.includes(null)) {
          this.$message.warning("打单列表中存在没有单号的订单，请重新选择")
          return
        }

        const data = this.selectionList.map((ele, index) => {
          return {
            code: ele.code,
            barcodeData: ele.originNo,
            address: ele.receiverAddress + ele.receiverAddressDetail,
            receiver: ele.receiverName,
            telephone: ele.receiverPhone,
            distance: `${ele.distance} 公里`,
            baseAddress: ele.baseAddress,
            info: ele.orderRemark,
            remark: ele.remark1,
            page: `${index + 1} / ${this.selectionList.length}`
          }
        })
        $("#hiprint-printTemplate").empty()
        const hiprintTemplate = new hiprint.PrintTemplate({
          template: this.printTemplate,
          settingContainer: "#PrintElementOptionSetting",
        });
        if (hiprint.hiwebSocket.opened) {
          hiprintTemplate.print2(data, {
            printer: this.printer,
            title: '打单',
            color: false,
            copies: 1
          })
        } else {
          hiprintTemplate.print(data, {})
        }
        hiprintTemplate.on('printSuccess', function (e) {
          console.log('打印成功');
        })
        hiprintTemplate.on('printError', function (e) {
          console.log('打印错误');
        })

        this.selectionList.forEach(row => {
          updatePrintStatus(row.id).then(() => {})
        })
        if (this.printVisible) {
          this.handlePrintClose()
          this.onLoad(this.page)
        }
      },
      handleGeneral() {
        if (!this.date || this.date === '') {
          this.$message.warning("请先选择要生成单号的日期!");
          return;
        }
        this.$confirm(`确定生成${this.date}的物流数据?`, {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return general(this.date);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleOrder() {
        if (!this.date || this.date === '') {
          this.$message.warning("请先选择要下单的日期!");
          return;
        }
        this.$confirm(`确定下单${this.date}的物流订单?`, {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return sfOrder(this.date);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      print(token, row, seq, sum) {
        const data = {
          requestID: this.uuid(),
          accessToken: token,
          templateCode: "fm_76165_standard1_JMQSAPATNAFU",
          customTemplateCode: 'fm_76165_standard1_custom_10021794636_5',
          documents: [
            {
              masterWaybillNo: row.originNo,
              // remark: `托寄物: ${row.depositum ? row.depositum : '特殊餐'}\n备注: ${row.orderRemark}\n其他备注: ${row.remark1 ? row.remark1 : '无'}`,
              payment: '寄付月结',
              printIcons: ['标快'],
              customData: {remark: `托寄物: ${row.depositum ? row.depositum : '特殊餐'}\n备注: ${row.orderRemark}\n其他备注: ${row.remark1 ? row.remark1 : '无'}`}
            }
          ],
        };
        printSdk.print(data, (res) => {
          if (res.msg === 'success') {
            updatePrintStatus(row.id).then(() => {})
          }
        }, {
          lodopFn: "PRINT"
        });
      },
      uuid() {
        const temp_url = URL.createObjectURL(new Blob());
        const uuid = temp_url.toString();
        URL.revokeObjectURL(temp_url);
        return uuid.substr(uuid.lastIndexOf("/") + 1);
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      handleCancelConfirm() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定取消确认?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return cancelConfirm(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      handleCancelConfirmItem(row) {
        this.$confirm("确定取消确认?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return cancelConfirm(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      handleCancelSF() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据取消顺丰订单?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return cancelSF(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        if (this.date && this.date !== '') {
          params.date = this.date
        }
        if (this.hasSpec && this.hasSpec !== '') {
          params.hasSpec = this.hasSpec
        }
        if (this.printStatus !== undefined && this.printStatus !== '') {
          params.printStatus = this.printStatus
        }
        if (this.deliveryStatus && this.deliveryStatus !== '') {
          params.deliveryStatus = this.deliveryStatus
        }
        if (this.remark && this.remark !== '') {
          params.remark = this.remark
        }
        if (this.searchMerchantId && this.searchMerchantId !== '') {
          params.merchantId = this.searchMerchantId
        }
        if (this.nicknameAndPhone && this.nicknameAndPhone !== '') {
          params.nicknameAndPhone = this.nicknameAndPhone
        }
        if (this.dateRange && this.dateRange !== '') {
          params.startDate = this.dateRange[0]
          params.endDate = this.dateRange[1]
        }
        params.showCancel = this.showCancel
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style lang="scss">
.el-form-item {
  margin-right: 20px;
}
.el-input__icon {
  height: auto;
}
.avue-crud .el-input__inner, .avue-form .el-input__inner {
  height: 32px;
}
.el-select-dropdown .el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
  padding: 0 20px !important;
}
</style>
